#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from PageObjects.WebQQ.QQBasePage import QQBasePage
from Utils.Element import Element
from Utils.PropertiesParsor import ParsePageProperty
from Config.GlobalVariables import OPERATION_ATTEMPT
import time

parse_string = ParsePageProperty().parse_string
parse_locator = ParsePageProperty().parse_locator
set_property_value = ParsePageProperty().set_property_value


class QQHomePage(QQBasePage):

    @staticmethod
    def parse_url():
        return parse_string('WebQQ.HomePage.url')

    @staticmethod
    def parse_title():
        return parse_string('WebQQ.HomePage.title')

    @staticmethod
    def contact_to(name):
        return parse_string('WebQQ.HomePage.contact_to').format(name)

    def talk_button(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.talk_button'))

    def contact_button(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_button'))

    def contact_friend_tab(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_friend_tab'))

    def contact_group_tab(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_group_tab'))

    def contact_discuss_tab(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_discuss_tab'))

    def contact_search_button(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_search_button'))

    def contact_search_textbox(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.contact_search_textbox'))

    def contact_result(self, name):
        locate_type = parse_locator('WebQQ.HomePage.contact_result')[0]
        locate_expression = parse_locator('WebQQ.HomePage.contact_result')[1].format(name)
        return Element(self.driver, (locate_type, locate_expression))

    def chat_panel(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.chat_panel'))

    def chat_textbox(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.chat_text_box'))

    def chat_send_button(self):
        return Element(self.driver, parse_locator('WebQQ.HomePage.chat_send_button'))

    def set_cookies_opt(self):
        self.logger.info("Set WebQQ Cookies")
        try:
            if self.talk_button().is_displayed():
                self.logger.debug("Get Page Cookies Successfully")
                cookies = self.driver.get_cookies()
                self.logger.debug("Set Page Cookies Into PageProperty Cookies")
                set_property_value("WebQQ.HomePage.cookies", cookies)
            else:
                self.logger.debug("Set Empty List Into PageProperty Cookies")
                set_property_value("WebQQ.HomePage.cookies", [])
        except Exception as e:
            self.logger.error("Failed To Set Cookies Property: {0}".format(e))
            raise e

    def go_(self):
        self.logger.info("Let's Go WebQQ")
        self.browser.new_window(parse_string("WebQQ.HomePage.url"))
        self.browser.switch_to_last_window()
        cookies = parse_string("WebQQ.HomePage.cookies")
        if cookies:
            self.logger.debug("Add cookies to page and refresh")
            for cookie in cookies:
                self.add_cookie(cookie)
            self.browser.refresh()
            return True
        else:
            for login_attempt in range(OPERATION_ATTEMPT):
                self.logger.debug("Check whether WebQQ is logged in")
                if self.talk_button().is_displayed():
                    self.logger.debug("WebQQ is logged in")
                    return True
                else:
                    self.logger.info("Login NO.{0} Attempts".format(login_attempt + 1))
            return False

    def go(self):
        if not self.go_():
            self.logger.error("Cannot Login In {0} Attempts, Quit".format(OPERATION_ATTEMPT))
            self.browser.close()
            self.browser.switch_to_first_window()
            return False
        else:
            self.set_cookies_opt()
            if parse_string("WebQQ.HomePage.cookies"):
                self.logger.error("Fail To Set Page Cookies, Quit")
                self.browser.close()
                self.browser.switch_to_first_window()
                return False
            else:
                self.logger.info("Login And Set Page Cookies Successfully")
                self.browser.close()
                self.browser.switch_to_first_window()
                return True

    def send_messages_(self, target_contact, message_content):
        self.logger.info("Click contact button")
        self.contact_button().click()
        self.logger.info("Click search contact button")
        self.contact_search_button().click()
        self.logger.info("Input target contact in contact search textbox")
        self.contact_search_textbox().clear()
        self.contact_search_textbox().send_keys(target_contact)
        self.logger.info("Click searched target contact in contact search list")
        self.contact_result(target_contact).click()
        self.logger.info("Input message content in chat textbox")
        self.chat_textbox().clear()
        self.chat_textbox().send_keys(message_content)
        self.logger.info("Click send button")
        self.chat_send_button().click()

    def send_messages(self, webqq_window_index, target_contact, message_content):
        try:
            current_window = self.driver.current_window_handle
            self.browser.switch_to_specific_window(webqq_window_index)
            self.send_messages_(target_contact, message_content)
            self.driver.switch_to.window(current_window)
            time.sleep(2)  # Chrome issue, have to wait sometime after switching frame
        except Exception as e:
            self.logger.error("Cannot send messages via WebQQ")
            raise e
